package com.edu.convert;

import org.springframework.core.convert.converter.Converter;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;

public class MyStringToDateConverter implements Converter<String, Date> {
    @Override
    public Date convert(String source) {
        System.out.println("进入转化string-日期");
        Date date = null;
        Pattern PATTERN_1 = Pattern.compile("^\\d{4}-\\d{1,2}-\\d{1,2}$");
        Pattern PATTERN_2 = Pattern.compile("^\\d{4}/\\d{1,2}/\\d{1,2}$");
        Pattern PATTERN_3 = Pattern.compile("^\\d{4}\\\\\\d{1,2}\\\\\\d{1,2}$");
        if (PATTERN_1.matcher(source).matches()) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            try {
                date = sdf.parse(source);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            return date;
        } else if (PATTERN_2.matcher(source).matches()) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
            try {
                date = sdf.parse(source);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            return date;
        } else if (PATTERN_3.matcher(source).matches()) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy\\MM\\dd");
            try {
                date = sdf.parse(source);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            return date;
        }
        return null;
    }
}
